package com.daikting.bloodservice;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by daikting on 2017/9/1.
 */

public class BloodActivity extends Activity {
    UsbManager mUsbManager = null;
    UsbDevice myUsbDevice = null;
    UsbInterface Interface1, Interface2 = null;
    UsbEndpoint epIntEndpointOut, epIntEndpointIn;
    UsbDeviceConnection conn = null;
    UsbDeviceConnection myDeviceConnection;
    OnStateListener onStateListener;
    String[] a = null;
    protected static final String ACTION_USB_PERMISSION = "ch.serverbox.android.USB";  //USB插入时授权广播
    private boolean isRun = false;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    isRun = false;
                    if (a == null) {
                        onStateListener.onStateListener(State.TestFailed, null);
                    } else {

                        String status = changeHex(a[3]) == "0" ? "正常" : "心率不齐";
//                        String result = "高压：" + changeHex(a[0]) + "  低压：" + changeHex(a[1]) + "  心率：" + changeHex(a[2]) + " " + status;

                        ResultBean resultBean = new ResultBean();
                        resultBean.setMaximumPressure(changeHex(a[0]));
                        resultBean.setMinimumPressure(changeHex(a[1]));
                        resultBean.setHeartRate(changeHex(a[2]));
                        resultBean.setState(status);
                        onStateListener.onStateListener(State.TestSuccess, resultBean);
                    }

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    }

    private void receiveMessageFromPoint() {
        if (myDeviceConnection == null || epIntEndpointIn == null) {
            return;
        }
        new Thread() {
            @SuppressLint("NewApi")
            @Override
            public void run() {
                while (isRun) {
                    int ret = 0;
                    String Bytes[] = new String[8];
                    byte[] mReadDataBuff = new byte[64]; //default 8
                    if ((ret = myDeviceConnection.bulkTransfer(epIntEndpointIn, mReadDataBuff, mReadDataBuff.length, 2000)) < 0) {

                    } else {
                        for (int index = 0; index < Bytes.length; index++) {
                            Bytes[index] = (String.format("%02X", mReadDataBuff[index]));
                        }
                        if (Bytes[0].equals("F3")) {
                        } else if (Bytes[0].equals("F7")) {
                            a = decimalist(Bytes, 5);
                            handler.sendEmptyMessage(0);
                        }
                    }
                }
            }
        }.start();
    }

    private String[] decimalist(String[] s, int num) {
        String[] str = new String[num];
        str[0] = s[2]; //高压
        str[1] = s[3]; //低压
        str[2] = s[4]; //心率
        str[3] = s[5]; //0:无心率不齐   1:出现心律不齐
        str[4] = s[6]; //错误信息
        return str;

    }

    private String changeHex(String hexStr) {
        return String.valueOf(Integer.parseInt(hexStr, 16));
    }

    /**
     * 请求授权
     */
    public void requestAuth() {
        if (myUsbDevice == null) {
            //Toast.makeText(MainActivity.this, "device 授权失败", Toast.LENGTH_SHORT).show();
            Log.d("BloodTest","myUsbDevice == null");
            onStateListener.onStateListener(State.AuthFailed, null);
            return;
        }
        for (int i = 0; i < myUsbDevice.getInterfaceCount(); i++) {
            UsbInterface intf = myUsbDevice.getInterface(i);
            String authInfo = "成功\n"
                    + "EndpointCount:" + intf.getEndpointCount() + "\n"
                    + "Id:" + intf.getId() + "\n"
                    + "InterfaceClass:" + intf.getInterfaceClass() + "\n"
                    + "InterfaceProtocol:" + intf.getInterfaceProtocol() + "\n"
                    + "InterfaceSubclass:" + intf.getInterfaceSubclass();
            Log.d("BloodTest",authInfo);
            if (i == 1) {
                Interface2 = intf;
            }
        }
        if (Interface2 == null) {
            //Toast.makeText(MainActivity.this, "device 分配端点失败", Toast.LENGTH_SHORT).show();
            Log.d("BloodTest","Interface2 == null");
            onStateListener.onStateListener(State.AuthFailed, null);
            return;
        }
        for (int i = 0; i < Interface2.getEndpointCount(); i++) {
            UsbEndpoint ep = Interface2.getEndpoint(i);
            if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
                String pointInfo = "成功\n"
                        + "Type:" + ep.getType() + "\n"
                        + "Address:" + ep.getAddress() + "\n"
                        + "Attributes:" + ep.getAttributes() + "\n"
                        + "Direction:" + ep.getDirection() + "\n"
                        + "EndpointNumber:" + ep.getEndpointNumber() + "\n"
                        + "Interval:" + ep.getInterval() + "\n"
                        + "MaxPacketSize:" + ep.getMaxPacketSize();
                Log.d("BloodTest",pointInfo);
                if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                    epIntEndpointOut = ep;
                }
                if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                    epIntEndpointIn = ep;
                }
            }
        }

        // 在open前判断是否有连接权限；对于连接权限可以静态分配，也可以动态分配权限
        if (mUsbManager.hasPermission(myUsbDevice)) {
            conn = mUsbManager.openDevice(myUsbDevice);
        }
        if (conn == null) {
            Log.d("BloodTest","conn == null");
            onStateListener.onStateListener(State.AuthFailed, null);
            return;
        }

        if (conn.claimInterface(Interface2, true)) {
            myDeviceConnection = conn;
            //Toast.makeText(this, "open设备成功！", Toast.LENGTH_SHORT).show();
        } else {
            // Toast.makeText(this, "无法打开连接通道", Toast.LENGTH_SHORT).show();
            onStateListener.onStateListener(State.AuthFailed, null);
            conn.close();
            return;
        }

        onStateListener.onStateListener(State.AuthSuccess, null);
    }

    public void checkState() {
        HashMap<String, UsbDevice> devlist = mUsbManager.getDeviceList();
        //Toast.makeText(MainActivity.this, "devlist:"+devlist.size(), Toast.LENGTH_SHORT).show();
        if (!devlist.isEmpty()) {
            Iterator<UsbDevice> deviter = devlist.values().iterator();
            while (deviter.hasNext()) {
                UsbDevice d = deviter.next();
                if (d.getVendorId() == 0xe0b6 && d.getProductId() == 0x0d11) {
                    myUsbDevice = d;
                    String deviceInfo = "成功\n"
                            + "vid:" + d.getVendorId() + " piv:" + d.getProductId() + "\n"
                            + "DeviceName:" + d.getDeviceName() + "\n"
                            + "DeviceProtocol:" + d.getDeviceProtocol() + "\n"
                            + "DeviceSubclass:" + d.getDeviceSubclass() + "\n"
                            + "InterfaceCount:" + d.getInterfaceCount() + "\n"
                            + "DeviceId:" + d.getDeviceId() + "\n"
                            + "InterfaceCount:" + d.getInterfaceCount() + "\n"
                            + "DeviceClass:" + d.getDeviceClass();
                }
            }
            if (myUsbDevice == null) {
                //Toast.makeText(MainActivity.this, "device 授权失败", Toast.LENGTH_SHORT).show();
                onStateListener.onStateListener(State.CheckFailed, null);
                return;
            }
            PendingIntent pi = PendingIntent.getBroadcast(
                    this, 0, new Intent(
                            ACTION_USB_PERMISSION), 0);

            mUsbManager.requestPermission(myUsbDevice, pi);
            onStateListener.onStateListener(State.CheckSuccess, null);
        }else{

            onStateListener.onStateListener(State.CheckFailed, null);
        }
    }

    /**
     * 开始测试
     */
    public void startTest() {
        byte bytes[] = new byte[8];
        if (myDeviceConnection == null || epIntEndpointOut == null) {
            onStateListener.onStateListener(State.Disconnected, null);
            return;
        }
        onStateListener.onStateListener(State.TestStart, null);
        // bulkOut传输
        bytes[0] = (byte) 0xF3;
        bytes[1] = (byte) 0x01;
        bytes[2] = (byte) 0x01;
        bytes[3] = (byte) 0x9a;
        bytes[4] = (byte) 0x00;
        bytes[5] = (byte) 0x00;
        bytes[6] = (byte) 0x00;
        bytes[7] = (byte) 0x00;
        if (myDeviceConnection.bulkTransfer(epIntEndpointOut, bytes,
                bytes.length, 0) < 0) {
        } else {
            isRun = true;
            receiveMessageFromPoint();
        }
    }

    /**
     * 结束测试
     */
    public void stopTest() {
        byte bytes[] = new byte[8];
        if (myDeviceConnection == null || epIntEndpointOut == null) {
            onStateListener.onStateListener(State.Disconnected, null);
            return;
        }
        // bulkOut传输
        bytes[0] = (byte) 0xF3;
        bytes[1] = (byte) 0x01;
        bytes[2] = (byte) 0x02;
        bytes[3] = (byte) 0x78;
        bytes[4] = (byte) 0x00;
        bytes[5] = (byte) 0x00;
        bytes[6] = (byte) 0x00;
        bytes[7] = (byte) 0x00;
        if (myDeviceConnection.bulkTransfer(epIntEndpointOut, bytes,
                bytes.length, 0) < 0) {
        } else {
            isRun = false;
        }
    }

    public void setOnStateListener(OnStateListener onStateListener) {
        this.onStateListener = onStateListener;
    }

    public interface OnStateListener {
        void onStateListener(State state, ResultBean resultBean);
    }

    public enum State {
        AuthFailed, AuthSuccess,
        CheckFailed,CheckSuccess,
        Disconnected,
        TestStart, TestSuccess, TestFailed
    }

    public class ResultBean {
        String maximumPressure = "";
        String minimumPressure = "";
        String heartRate = "";
        String state = "";

        public String getMaximumPressure() {
            return maximumPressure;
        }

        public void setMaximumPressure(String maximumPressure) {
            this.maximumPressure = maximumPressure;
        }

        public String getMinimumPressure() {
            return minimumPressure;
        }

        public void setMinimumPressure(String minimumPressure) {
            this.minimumPressure = minimumPressure;
        }

        public String getHeartRate() {
            return heartRate;
        }

        public void setHeartRate(String heartRate) {
            this.heartRate = heartRate;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }
    }
}